package com.resou.reader.mine.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.resou.reader.R;
import com.resou.reader.base.v.BaseActivity;
import com.resou.reader.mine.IView.IPhoneBindView;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.presenter.PhoneBindPresenter;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.log.RsLog;
import com.resou.reader.view.Loading;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PhoneBindActivity extends BaseActivity<PhoneBindPresenter> implements IPhoneBindView {

    @BindView(R.id.phone_number_edit)
    AppCompatEditText mNumberInput;
    @BindView(R.id.get_verify_code_text)
    TextView mGetVerifyCodeText;
    @BindView(R.id.verify_code_edit)
    AppCompatEditText mVerifyInput;
    @BindView(R.id.btn_login)
    Button mLoginBtn;

    @BindView(R.id.bind_parent)
    View bindGroup;
    @BindView(R.id.already_bind_parent)
    View mAlreadyBindGroup;
    @BindView(R.id.bind_text)
    TextView mBindText;
//    @BindView(R.id.phone_number_edit_container)
//    TextInputLayout phoneNumberEditContainer;

    @Override
    public int getLayoutId() {
        return R.layout.activity_phone_bind;
    }

    @Override
    protected void initPresenter() {
        presenter = new PhoneBindPresenter(this);
    }

    @Override
    protected void initView() {
        mNumberInput.addTextChangedListener(textWatcher);
        mVerifyInput.addTextChangedListener(textWatcher);
        setLoginBtnState();
        switchViewState(TextUtils.isEmpty(UserInstance.getLoginData().getPhone()));
    }

    @Override
    protected void retryRefreshData() {

    }

    @Override
    public Context getViewContext() {
        return this;
    }

    @OnClick({R.id.btn_login, R.id.get_verify_code_text, R.id.btn_change_phone})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                if (NetworkUtils.isNetworkConnected(this)) {
                    Loading.getInstance().show(getSupportFragmentManager());
                    presenter.bindMobile(mNumberInput.getText().toString(), mVerifyInput.getText().toString());
                } else {
                    ToastUtil.makeShortToast("网络异常");
                }
                break;
            case R.id.get_verify_code_text:
                if (NetworkUtils.isNetworkConnected(this)) {
                    presenter.sendSMSCode(mNumberInput.getText().toString());
                    mGetVerifyCodeText.setClickable(false);
                    mGetVerifyCodeText.setTextColor(getResources().getColor(R.color.color_gray));
                    startCountDown();
                } else {
                    ToastUtil.makeShortToast("网络异常");
                }

                break;
            case R.id.btn_change_phone:
                switchViewState(true);
                break;
        }
    }

    private CountDownTimer timer;

    private void startCountDown() {
        if (timer == null) {
            timer = new CountDownTimer(60 * 1000, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    mGetVerifyCodeText.setText(millisUntilFinished / 1000 + getString(R.string.user_get_code_until_finished));
                    mGetVerifyCodeText.setClickable(false);
                }

                @Override
                public void onFinish() {
                    mGetVerifyCodeText.setText(getString(R.string.user_login_get_code));
                    mGetVerifyCodeText.setTextColor(getResources().getColor(R.color.btn_login_highlight));
                    mGetVerifyCodeText.setClickable(true);
                }
            };
        }
        timer.start();
    }

    private void setLoginBtnState() {
        boolean clickable = !TextUtils.isEmpty(mNumberInput.getText()) && mNumberInput.getText().toString().length() == 11 &&
                !TextUtils.isEmpty(mVerifyInput.getText()) && mVerifyInput.getText().toString().length() == 6;
        RsLog.d("clickable : " + clickable);
        mLoginBtn.setPressed(!clickable);
        mLoginBtn.setClickable(clickable);
        if (!TextUtils.isEmpty(mNumberInput.getText()) && mNumberInput.getText().toString().length() == 11) {
            mGetVerifyCodeText.setTextColor(getResources().getColor(R.color.btn_login_highlight));
            mGetVerifyCodeText.setClickable(true);
        } else {
            mGetVerifyCodeText.setTextColor(getResources().getColor(R.color.color_gray));
            mGetVerifyCodeText.setClickable(false);
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            setLoginBtnState();
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    @Override
    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void bindSuccess() {
        Loading.getInstance().dismiss();
        toast("绑定成功");
        switchViewState(false);


        mNumberInput.setText("");
        mVerifyInput.setText("");
        if (timer != null) {
            timer.onFinish();
        }
    }

    @Override
    public void bindError(String msg) {
        Loading.getInstance().dismiss();
        toast(msg);
    }

    private void switchViewState(boolean isToBind) {
        if (isToBind) {
            bindGroup.setVisibility(View.VISIBLE);
            mAlreadyBindGroup.setVisibility(View.GONE);
//            mNumberInput.setFocusableInTouchMode(true);
//            mNumberInput.setFocusable(true);
            mNumberInput.requestFocus();
//            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//            inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

            // 获取编辑框焦点
//            mNumberInput.setFocusable(true);
//            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//            if (inputMethodManager != null) {
//                inputMethodManager.showSoftInput(mNumberInput,InputMethodManager.SHOW_FORCED);
//            }
            //打开软键盘
//            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//            if (imm != null) {
//                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//            }

            //关闭软键盘
//            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

        } else {
            bindGroup.setVisibility(View.GONE);
            mAlreadyBindGroup.setVisibility(View.VISIBLE);
            mBindText.setText(getString(R.string.bind_phone) + "：" + UserInstance.getLoginData().getPhone());
        }
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, PhoneBindActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }
}
